package timetable.student;

import static android.provider.BaseColumns._ID;
import static timetable.student.Constants.DAY;
import static timetable.student.Constants.LECTURER;
import static timetable.student.Constants.MODULE;
import static timetable.student.Constants.ROOM;
import static timetable.student.Constants.TABLE_NAME;
import static timetable.student.Constants.TIMEEND;
import static timetable.student.Constants.TIMESTART;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

public class TimeTable extends Activity{
	private static final int ADD_CLASS = 0;
	private static String[] FROM = { _ID, DAY, MODULE, LECTURER,ROOM,TIMESTART,TIMEEND };
	private static String ORDER_BY = DAY+", "+TIMESTART + " ASC";
	private TimeTableData events;
	ExpandableListAdapter mAdapter;
	ExpandableListView listView ;
	
	ExpandableListView.ExpandableListContextMenuInfo info;
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timetabletab);
       
        listView = (ExpandableListView) findViewById(R.id.listView);
        listView.setBackgroundResource(R.drawable.customshape);
        mAdapter = new ExpandableListAdapter(this,  new ArrayList<ArrayList<Tdata>>());
        listView.setOnChildClickListener(new OnChildClickListener()
        {
            
            @Override
            public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2, int arg3, long arg4)
            {
            	try
            	{
            	Tdata t = (Tdata)mAdapter.getChild(arg2, arg3);
            	AlertDialog.Builder alertbox = new AlertDialog.Builder(TimeTable.this);
            	alertbox.setTitle(t.getModule());
            	//show the start time, end time, room -
            	
                alertbox.setMessage("Start Time: "+ t.getStartTime()+"\n"
                		+"End Time: "+t.getEndTime()+"\n"
                		+"Room: "+t.getRoom());
                alertbox.setNeutralButton("Close", new DialogInterface.OnClickListener() {

                    // Click listener on the neutral button of alert box
                    public void onClick(DialogInterface arg0, int arg1) {
                        
                    }
                });
                alertbox.show();
                return false;
            	}
            	catch (Exception e)
            	{
            		return false;
            	}
            }
        });
        listView.setAdapter(mAdapter);
         events = new TimeTableData(this); 
	      try {
	    	  //clearall();
	    	  Cursor cursor = getEvents(); 
	         showEvents(cursor);
	         
	      } finally {
	         events.close(); 
	      }
	      registerForContextMenu(listView);
	    
    }
	@Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo)menuInfo;
		int type = ExpandableListView.getPackedPositionType(info.packedPosition);
		if(type == ExpandableListView.PACKED_POSITION_TYPE_CHILD)
		{
			menu.setHeaderTitle("Class Menu");
			        
	        menu.add(0, 0, 0,"Modify" );
	        menu.add(0, 0, 0,"Delete" );
		}
		if(type == ExpandableListView.PACKED_POSITION_TYPE_GROUP)
		{
			menu.setHeaderTitle("Class Menu");
	        
	        menu.add(0, 0, 0,"Add New Class" );
		}
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        info = (ExpandableListView.ExpandableListContextMenuInfo)item.getMenuInfo();
       if(item.getTitle().toString().equals("Delete"))
       {
    	   //show alert with yes/no
    	   
    	   AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
    	   alertbox.setTitle("Confirm");
           alertbox.setMessage("Are you sure you want to delete this class?");
           alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {

                   int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
                   int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition); 
                   Tdata t = (Tdata)mAdapter.getChild(groupPos, childPos);
                   deleteRecord(t.getId());
              }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
           alertbox.show();
    	   return true;
    	   
    	}else if(item.getTitle().toString().equals("Modify"))
    	{    		
    		 int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
             int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition); 
             Tdata t = (Tdata)mAdapter.getChild(groupPos, childPos);
             String id = Integer.toString(t.getId());
    		String[] temp = new String[]{t.getDay(),t.getModule(),t.getLecturer(),t.getRoom(),t.getStartTime(),t.getEndTime(),id};
     		Intent i = new Intent(this,AddClass.class);
    	    i.putExtra("TDATA", temp);
    		startActivityForResult(i, ADD_CLASS);
    	}
    	else if(item.getTitle().toString().equals("Add New Class"))
    	{    		
    		int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
    		Intent i = new Intent(this,AddClass.class);
    		i.putExtra("GROUP_NUMBER", groupPos);

    		startActivityForResult(i, ADD_CLASS);
    		
    	}
        
        
        
        

        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        

        return false;
    }
	public void onActivityResult(int requestCode, int resultCode, Intent intent) 
	    {

	      if (requestCode == ADD_CLASS)
	      { 
	    		mAdapter.clear();
	    	   events = new TimeTableData(this); 
	 	      try {
	 	    	  
	 	    	  Cursor cursor = getEvents(); 
	 	         showEvents(cursor);
	 	         
	 	      } finally {
	 	         events.close(); 
	 	      } 
	    	  
	    	  
	        // Your class variables now have the data, so do something with it.
	      }
	     
	    }
	
	
	private void clearall()
	{
		SQLiteDatabase db = events.getWritableDatabase();
		db.delete(TABLE_NAME, null, null);
	}
	private void addEvent(String string) {
	    // Insert a new record into the Events data source.
	    // You would do something similar for delete and update.
	    SQLiteDatabase db = events.getWritableDatabase();
	    ContentValues values = new ContentValues();
	    values.put(DAY, 1);
	    values.put(MODULE, "CNET111");
	    values.put(LECTURER, "MR Davis");
	    values.put(ROOM,"B1020");
	    values.put(TIMESTART, System.currentTimeMillis());
	    values.put(TIMEEND, 292);
	    db.insertOrThrow(TABLE_NAME, null, values);
	 }
	private void deleteRecord(int id)
	{
		String arg = Integer.toString(id);
		SQLiteDatabase db = events.getWritableDatabase();
		db.delete(TABLE_NAME,"_ID=? ",new String[] {arg});
		mAdapter.clear();
		 events = new TimeTableData(this); 
	      try {
	    	  
	    	  Cursor cursor = getEvents(); 
	         showEvents(cursor);
	         
	      } finally {
	         events.close(); 
	      } 
		
		
		
	}
	private Cursor getEvents() {
	        // Perform a managed query. The Activity will handle closing
	        // and re-querying the cursor when needed.
	        SQLiteDatabase db = events.getReadableDatabase();
	        Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
	              null, ORDER_BY);
	        startManagingCursor(cursor);
	        return cursor;
	     }
	private void showEvents(Cursor cursor) {
	    while (cursor.moveToNext()) { 
	    	int id = cursor.getInt(0);
	       int day = cursor.getInt(1);
	       String module = cursor.getString(2);
	       String lectuerer = cursor.getString(3);
	       String room = cursor.getString(4);
	       String startTime = cursor.getString(5);
	       String endTime = cursor.getString(6);
	       mAdapter.addItem(new Tdata(id,day, module, lectuerer, room, startTime, endTime));
	    }
	    // Display on the screen
	    mAdapter.notifyDataSetChanged();
	
	 }
	
}
